# -*- coding: utf-8 -*-
import logging

import requests


class RidingRouteService:
    def __init__(self, api_key):
        self.base_url = "https://api.map.baidu.com/directionlite/v1/riding"
        self.api_key = api_key
        self.logger = logging.getLogger(__name__)

    def validate_coordinate(self, coord):
        try:
            # 拆分并转换坐标值为浮点数
            lat_str, lng_str = coord.split(',')
            if len(lat_str.split('.')[1]) > 6 or len(lng_str.split('.')[1]) > 6:
                raise ValueError("小数点精度超过6位")
            
            lat = float(lat_str)
            lng = float(lng_str)
            
            if not (-90 <= lat <= 90 and -180 <= lng <= 180):
                raise ValueError("坐标值超出范围")
                
            return True
        except (ValueError, AttributeError, IndexError) as e:
            self.logger.error(f"坐标验证失败: {coord} | 错误: {str(e)}")
            return False

    def get_riding_route(self, origin, destination, riding_type=0, road_prefer=0, **kwargs):
        if not all(self.validate_coordinate(c) for c in [origin, destination]):
            raise ValueError("坐标格式应为'纬度,经度'且小数精度不超过6位")
        
        if riding_type not in [0, 1, 2]:
            raise ValueError("骑行类型参数错误，可选值: 0-普通骑行,1-电动车,2-摩托车")

        params = {
            'origin': origin,
            'destination': destination,
            'ak': self.api_key,
            'riding_type': riding_type,
            'road_prefer': road_prefer,
            **kwargs
        }

        try:
            response = requests.get(self.base_url, params=params, timeout=10)
            response.raise_for_status()
            data = response.json()

            if data.get('status') != 0:
                error_msg = data.get('message', '未知错误')
                self.logger.error(f"百度API错误: {error_msg}")
                return None

            return self._parse_api_response(data)

        except requests.exceptions.RequestException as e:
            self.logger.error(f"请求异常: {str(e)}")
            return None
        except (KeyError, IndexError) as e:
            self.logger.error(f"响应解析异常: {str(e)}")
            return None

# 使用示例
if __name__ == "__main__":
    service = RidingRouteService(api_key="47jXQbiwPNWVY5GgVPUJYpOiHG5YhBcr")
    result = service.get_riding_route(
        origin="20.011160,110.339303",
        destination="19.936404,110.452562",
        riding_type=0
    )
    print(result)


    # 骑行道路类型映射
    ROAD_TYPE_MAP = {
        0: '高速路', 1: '城市高速路', 2: '国道',
        3: '省道', 4: '县道', 5: '乡镇村道',
        6: '其他道路', 7: '九级路', 8: '轮渡航线', 9: '行人道路'
    }

    # 转向指示映射
    TURN_DIRECTION_MAP = {
        0: '无效', 1: '直行', 2: '右前方转弯',
        3: '右转', 4: '右后方转弯', 5: '掉头',
        6: '左后方转弯', 7: '左转', 8: '左前方转弯'
    }

    def _parse_direction(self, direction):
        start_angle = 345 - (direction * 30)
        if start_angle < 0:
            start_angle += 360
        end_angle = (start_angle + 30) % 360
        return f'{start_angle}°-{end_angle}°'

    def _parse_step(self, step):
        return {
            'direction': self._parse_direction(step.get('direction', 0)),
            'turn_type': self.TURN_DIRECTION_MAP.get(step.get('turn_type', 0), '未知转向'),
            'distance': step['distance'],
            'duration': step['duration'],
            'road_types': [self.ROAD_TYPE_MAP.get(int(rt)) for rt in step.get('road_types', '').split(',') if rt],
            'road_name': step.get('road_name', '无名路'),
            'instruction': step['instruction'],
            'path': [tuple(map(float, loc.split(','))) for loc in step.get('path', '').split(';')]
        }

    def _parse_api_response(self, data):
        result = data['result']
        route = result['routes'][0]

        return {
            'origin': {
                'lng': result['origin']['lng'],
                'lat': result['origin']['lat']
            },
            'destination': {
                'lng': result['destination']['lng'],
                'lat': result['destination']['lat']
            },
            'distance': route['distance'],
            'duration': route['duration'],
            'steps': [self._parse_step(s) for s in route['steps']]
        }